package com.gzu.shop.controller;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.gzu.shop.base.BaseController;
import com.gzu.shop.common.Result;
import com.gzu.shop.constant.JwtClaimsConstant;
import com.gzu.shop.constant.MessageConstant;
import com.gzu.shop.constant.OrderStatusConstant;
import com.gzu.shop.constant.RoleConst;
import com.gzu.shop.context.BaseContext;
import com.gzu.shop.entity.*;
import com.gzu.shop.exception.AddressBookBusinessException;
import com.gzu.shop.exception.OrderBusinessException;
import com.gzu.shop.mapper.ProvinceMapper;
import com.gzu.shop.mapper.ThingMapper;
import com.gzu.shop.mapper.UserMapper;
import com.gzu.shop.param.SearchCondition;
import com.gzu.shop.service.OrderService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;

/**
 * @author Clown
 */
@Slf4j
@Tag(name = "用户订单相关接口")
@RestController
@RequestMapping("/order")
@AllArgsConstructor
public class OrderController extends BaseController<OrderService, Order> {
    private ThingMapper thingMapper;
    private ProvinceMapper provinceMapper;
    private UserMapper userMapper;
    @Override
    @Operation(description = "重写了父类方法，填充非数据库字段")
    @PostMapping("/page/{startPage}/{pageSize}")
    public Result<IPage<Order>> page(@PathVariable int startPage, @PathVariable int pageSize, @RequestBody(required = false) SearchCondition<Order> searchCondition) {

        // 获取用户信息
        Map<String, Object> threadLocal = BaseContext.getThreadLocal();
        // 取出userId,
        String role = (String) threadLocal.get(JwtClaimsConstant.ROLE);
        Integer userId = (Integer) threadLocal.get(JwtClaimsConstant.USER_ID);

//        System.out.println("###########");
//        log.info("role: {}", role);
//        log.info("userId: {}", userId);
//        log.info("order:{}", searchCondition.getSearch());

        // 如果为普通用户，添加用户id
        log.info("role:{}", role);
        if (RoleConst.USER.equals(role)) {
//            searchCondition.getSearch().setUserId(String.valueOf(userId));
            searchCondition.getFilter().setUserId(String.valueOf(userId));
        }

        // 获取所有订单
        Result<IPage<Order>> page = super.page(startPage, pageSize, searchCondition);
        List<Order> orders = page.getData().getRecords();
        // 遍历订单，填充商品属性
        for (Order order : orders) {
            Thing thing = thingMapper.selectById(order.getThingId());
            Province province = provinceMapper.selectById(order.getProvinceId());
            User user = userMapper.selectById(order.getUserId());
            order.setCover(thing.getCover());
            order.setPrice(thing.getPrice());
            order.setTitle(thing.getTitle());
            order.setUsername(user.getUsername());
            order.setProvinceName(province.getName());
//            order.setUsername(order1.getUsername());
        }
        // 重新设置分页数据
        page.getData().setRecords(orders);
//        orderService.page()
        return page;
    }

    @Override
    @Operation(summary = "重写父类方法，实现编辑实体功能")
    @PostMapping("/edit")
    public Result<Void> editById(@RequestBody Order entity) {
        // 判断订单状态
        // 如果为取消，更新取消时间
        // 如果为退款，更新退款时间
        log.info("order:{}", entity);
        Integer userId = getUserId(entity);

        if (OrderStatusConstant.REFUNDED.equals(entity.getStatus())) {
            entity.setRefundTime(String.valueOf(System.currentTimeMillis()));
        } else if (OrderStatusConstant.CANCELLED.equals(entity.getStatus())) {
            entity.setCancelTime(String.valueOf(System.currentTimeMillis()));
        }

//        System.out.println(entity);
        return super.editById(entity);
    }

    @Override
    @Operation(summary = "重写父类方法，实现添加订单功能")
    @PostMapping("/add")
    @Transactional
    public Result<Void> addEntity(@RequestBody Order entity) {
//        System.out.println("#################");
//        // 获取userId
//        // 获取用户ID
//        Map<String, Object> threadLocal = BaseContext.getThreadLocal();

        // 获取用户Id
        Integer userId = getUserId(entity);

        // 获取商品id
        String thingId = entity.getThingId();
        // 减少商品库存
        Thing thing = thingMapper.selectById(thingId);
        // 更新商品时间
        thing.setUpdateTime(String.valueOf(System.currentTimeMillis()));
        // 计算现在库存量, 更新商品Id
        thing.setRepertory(String.valueOf(Integer.parseInt(thing.getRepertory()) - Integer.parseInt(entity.getAmount())));
        // 更新商品Id
        thingMapper.updateById(thing);
        // 设置用户Id
        entity.setUserId(String.valueOf(userId));
        // 设置订单时间
        entity.setOrderTime(String.valueOf(System.currentTimeMillis()));

        // 设置支付时间
        if (Objects.equals(entity.getStatus(), OrderStatusConstant.PAID)) {
            entity.setPayTime(String.valueOf(System.currentTimeMillis()));
        }

        // 设置订单编号 当前时间 + UUID
        entity.setOrderNumber(String.valueOf(System.currentTimeMillis() + UUID.randomUUID().toString()));
        System.out.println(entity);
        return super.addEntity(entity);
    }


    // 判断关键字段是否为空，为空则抛出异常，获取userId
    private Integer getUserId(Order entity) {
        // entity为空
        if (entity == null) {
            throw new OrderBusinessException(MessageConstant.DATA_IS_NULL);
        }

        // 如果收货地址为空
        if (entity.getReceiverAddress() == null || entity.getReceiverAddress().isEmpty()) {
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_DETAIL_EMPTY);
        }

        // 如果收货人姓名为空
        if (entity.getReceiverName() == null || entity.getReceiverName().isEmpty()) {
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_RECEIVER_NAME_EMPTY);
        }

        // 如果收货省份为空
        if (entity.getProvinceId() == null || entity.getProvinceId().isEmpty()) {
            throw new AddressBookBusinessException(MessageConstant.RECEIVER_PROVINCE_NAME_EMPTY);
        }

        // 如果收货电话号码为空
        if (entity.getReceiverPhone() == null || entity.getReceiverPhone().isEmpty()) {
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_TELEPHONE_EMPTY);
        }
        // 数量为0
        if (Integer.parseInt(entity.getAmount()) == 0) {
            throw new OrderBusinessException(MessageConstant.ORDER_AMOUNT_EMPTY);
        }
        // 数量大于库存
        if (Integer.parseInt(entity.getAmount()) >
                Integer.parseInt(thingMapper.selectById(Integer.valueOf(entity.getThingId())).getRepertory())) {
            throw new OrderBusinessException(MessageConstant.ORDER_QUANTITY_MORE_THAN_INVENTORY);
        }

        // 填充userId
        // 获取userId
        // 获取用户ID
        Map<String, Object> threadLocal = BaseContext.getThreadLocal();
        return (Integer) threadLocal.get(JwtClaimsConstant.USER_ID);
    }
}
